
import Util from "../common/Util"
import Api from "../common/Api"
import NewsItem from "./news_item"
import NewsDetail from "./news_detail"
import BlogDetail from "../user/blog_detail"

import TopTabBar from "../common/TopTabBar"

var RefreshInfiniteListView = require('../common/RefreshInfiniteListView');
var React = require('react-native')
var {
  View,
  ListView,
  StyleSheet,
  Text,
  SegmentedControlIOS,
  ScrollView,
  AlertIOS,
}=React;

var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});

export default class News extends React.Component {
  constructor(props) {
    super(props)
  //  var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state={
      values: ['资讯', '热点', '博客','推荐'],
      selectedValue:'资讯',
      news:[],
      show: false,
      pageIndex:1,
      pageSize:20,
    }
  }

  componentDidMount(){
    console.log("componentDidMount")
    this._changeSegment('资讯');
  }

    _changeSegment(val){
      this.setState({
        news:[],
        show:false,
      })
      this._onRefresh(val);
    }

  /**
  * @description 头部向下拉刷新数据
  */
  _onRefresh(key){
    var url;
    if(key==='资讯'){
      url=Api.news_list;
    }else if(key==='热点'){
      url=Api.news_list+"?show=week";
    }else if(key==='博客'){
      url=Api.blog_list+"?type=latest";
    }else if(key==='推荐'){
      url=Api.blog_list+"?type=recommend";
    }
    this._reloadContent(url,true);
  }

  /**
  * @description 底部向上拉加载下一页数据
  */
  _reloadMore(key){
    var url='';
    if(key==='资讯'){
      url=Api.news_list+"?";
    }else if(key==='热点'){
      url=Api.news_list+"show=week";
    }else if(key==='博客'){
      url=Api.blog_list+"type=latest";
    }else if(key==='推荐'){
      url=Api.blog_list+"type=recommend";
    }
    url+='&pageSize='+this.state.pageSize;
    this.setState({
      pageIndex:this.state.pageIndex+1
    })
    url+='&pageIndex='+this.state.pageIndex;

    this._reloadContent(url,false);
  }

  _reloadContent(url,hideHeader){
    console.log('exec _reloadContent^^^')
    var that =this;
    Util.get(url,(data)=>{
      //console.log(JSON.stringify(data));
      //console.log(data.oschina.newslist.news);
      var d=[];
      new Promise(()=>{
        if(hideHeader){
          that.list.hideHeader();
          if(that.state.selectedValue==='资讯'||that.state.selectedValue==='热点'){
            d=data.oschina.newslist.news;
          }else{
            d=data.oschina.blogs.blog;
          }

        }else{
          that.list.hideFooter();
          if(that.state.selectedValue==='资讯'||that.state.selectedValue==='热点'){
            d=that.state.news.concat(data.oschina.newslist.news);
          }else{
            d=that.state.news.concat(data.oschina.blogs.blog);
          }

        }
        that.setState({
          news:d,
          show: true,
        })
      })
    });
  }

  _loadPage(id){
    if(this.state.selectedValue==='资讯'||this.state.selectedValue==='热点'){
      this.props.navigator.push({
        component:<NewsDetail id={id}/>,
        title: "资讯详情"
      })
    }else{
      this.props.navigator.push({
        component:<BlogDetail objid={id}/>,
      title: "博客详情"
      })
    }
  }

  _onInfinite(){

  }

  render(){
    return (
      <View style={styles.container}>
        <TopTabBar
          tabs={this.state.values}
          initTab={0}
          onValueChange={(val,i)=>{
            this.setState({
              selectedValue:val
            });
            this._changeSegment(val);
          }}
          />
        {/*
        <View style={[styles.newsTag]}>
          <SegmentedControlIOS
            tintColor='#4ead7d'
            style={styles.news_tag}
            selectedIndex={0}
            values={this.state.values}
            onValueChange={(val)=>{
              this.setState({
                selectedValue:val
              });
              this._changeSegment(val);
            }}
            />
        </View>
        */}
        {/*
        <ScrollView style={styles.newsListContent}>
          {this.state.show ?
          <ListView
            dataSource={this.state.newsList}
            renderRow={(row)=>
              <NewsItem row={row} onPress={this._loadPage.bind(this,row.id)} {...this.props}/>
            }
            />
          :Util.loading
          }
        </ScrollView>
        */}
        <RefreshInfiniteListView
            ref = {(list) => {this.list= list}}
            dataSource={ds.cloneWithRows(this.state.news)}
            renderRow={(row)=>
              <NewsItem row={row} onPress={this._loadPage.bind(this,row.id)} {...this.props}/>
            }
            loadedAllData={this._reloadMore.bind(this,this.state.selectedValue)}
            initialListSize={20}
            scrollEventThrottle={10}
            style={styles.newsListContent}
            onRefresh = {this._onRefresh.bind(this,this.state.selectedValue)}
            onInfinite = {this._onInfinite}
            >
        </RefreshInfiniteListView>

      </View>
    );
  }
}

var styles=StyleSheet.create({
  container:{
    backgroundColor:'rgb(235, 235, 243)',
    flex:1,
    marginTop:5,
    flexDirection:'column',
  },
  flex_row:{
    flexDirection:'row',
  },
  flex_column:{
    flexDirection:'column',
  },
  header:{
    alignItems:'center',
    height:30,
    marginTop:20,
    paddingTop:10,
    //backgroundColor:'#4ead7d',
  },
  newsTag:{

  },
  news_tag:{
    backgroundColor:'#f0e9eb',
    marginTop:-5,
  },
  newsListContent:{
    marginLeft:5,
    marginRight:2,
  }

});
